package com.ruoyi.web.controller.tool;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.domain.model.RegisterBody;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.exception.user.CaptchaExpireException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.SysWlyzUser;
import com.ruoyi.system.mapper.SysWlyzUserMapper;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * swagger 用户测试方法
 * 
 * @author ruoyi
 */
@Api("wot网络验证")
@RestController
@RequestMapping("/rest/wot/")
public class RestfulWotController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(RestfulWotController.class);

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private TokenService tokenService;

    private final static Map<Integer, WotUserEntity> users = new LinkedHashMap<Integer, WotUserEntity>();
    {
        users.put(1, new WotUserEntity("admin", "admin123", "15888888888"));
        users.put(2, new WotUserEntity("ry", "admin123", "15666666666"));
    }

    @ApiOperation("获取用户列表")
    @GetMapping("/list")
    public R<List<WotUserEntity>> userList()
    {
        List<WotUserEntity> userList = new ArrayList<WotUserEntity>(users.values());
        return R.ok(userList);
    }

    @ApiOperation("注册用户")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "username", value = "用户名", dataType = "String", dataTypeClass = String.class),
        @ApiImplicitParam(name = "password", value = "用户密码", dataType = "String", dataTypeClass = String.class),
        @ApiImplicitParam(name = "email", value = "用户邮箱", dataType = "String", dataTypeClass = String.class)
    })
    @PostMapping("/user/add")
    public String register(@Valid @RequestBody RegisterBody registerBody, HttpServletRequest request)
    {
        String msg = "", username = registerBody.getUsername(), password = registerBody.getPassword();
        SysUser sysUser = new SysUser();
        sysUser.setUserName(username);

        // 验证码开关
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (captchaEnabled)
        {
            validateCaptcha(username, registerBody.getCode(), registerBody.getUuid());
        }

        if (StringUtils.isEmpty(username))
        {
            msg = "用户名不能为空";
        }
        else if (StringUtils.isEmpty(password))
        {
            msg = "用户密码不能为空";
        }
        else if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            msg = "账户长度必须在2到20个字符之间";
        }
        else if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            msg = "密码长度必须在5到20个字符之间";
        }
        else if (!userService.checkUserNameUnique(sysUser))
        {
            msg = "保存用户'" + username + "'失败，注册账号已存在";
        }
        else
        {
            sysUser.setNickName(username);
            sysUser.setPassword(SecurityUtils.encryptPassword(password));
            boolean regFlag = userService.registerUser(sysUser);
            if (!regFlag)
            {
                msg = "注册失败,请联系系统管理人员";
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.REGISTER, MessageUtils.message("user.register.success")));
            }
        }
        return msg;
    }

    @ApiOperation("基础信息")
    @ApiImplicitParams({
    })
    @GetMapping("/user/info")
    public String info(HttpServletRequest request)
    {
        //数据库读取配置文件
        String version = configService.selectConfigByKey("sys.user.version");
        String downloadUrl = configService.selectConfigByKey("sys.user.downloadUrl");
        String gonggao = configService.selectConfigByKey("sys.user.gonggao");
        //包装JSON
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("version", version);
        jsonObject.put("downloadUrl", downloadUrl);
        jsonObject.put("gonggao", gonggao);
        String jsonString = jsonObject.toString();
        //返回
        return jsonString;
    }

    @ApiOperation("ase")
    @ApiImplicitParams({
    })
    @PostMapping("/user/aes")
    public String info(@Valid @RequestBody HeartBody heartBody, HttpServletRequest request) throws Exception {
        //包装JSON
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("encode", DesUtil.encrypt("a1b2c3d4",heartBody.getUnencodeString()));
        String jsonString = jsonObject.toString();
        return jsonString;
    }

    @ApiOperation("心跳包")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", dataType = "String", dataTypeClass = String.class)
    })
    @GetMapping("/sys/heart")
    public String heart(HttpServletRequest request)
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        SysWlyzUserMapper sysWlyzUserMapper = SpringUtils.getBean(SysWlyzUserMapper.class);
        SysWlyzUser sysWlyzUser = new SysWlyzUser();
        sysWlyzUser.setUserId(loginUser.getUserId());
        List<SysWlyzUser> wlyzUserList = sysWlyzUserMapper.selectSysWlyzUserList(sysWlyzUser);
        if (wlyzUserList.size()>0){
            sysWlyzUser = wlyzUserList.get(0);
            if (DateUtils.compareDate(sysWlyzUser.getCanLoginDate(),new Date()) < 0){
                throw new RuntimeException("登录时间已过，请重新登录");
            }
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai")); // 设置上海时区
        String formattedDate = dateFormat.format(sysWlyzUser.getCanLoginDate());

        String hexinConfig = configService.selectConfigByKey("sys.user.mainHexinConfig");
        String hexinConfig2 = configService.selectConfigByKey("sys.user.mainHexinConfig2");
        String hexinConfig3 = configService.selectConfigByKey("sys.user.mainHexinConfig3");
        String hexinConfig4 = configService.selectConfigByKey("sys.user.mainHexinConfig4");
        String beiyongziduan = configService.selectConfigByKey("sys.user.beiyongziduan");
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("code", "200");
            jsonObject.put("hexinConfig", DesUtil.encrypt("a1b2c3d4",hexinConfig));
            jsonObject.put("hexinConfig2", DesUtil.encrypt("a1b2c3d4",hexinConfig2));
            jsonObject.put("hexinConfig3", DesUtil.encrypt("a1b2c3d4",hexinConfig3));
            jsonObject.put("hexinConfig4", DesUtil.encrypt("a1b2c3d4",hexinConfig4));
            jsonObject.put("beiyongziduan", DesUtil.encrypt("a1b2c3d4",beiyongziduan));
            jsonObject.put("canlogindate", DesUtil.encrypt("a1b2c3d4", formattedDate));
        } catch (Exception e) {
            throw new RuntimeException("DES解析出错，请重新登录");
        }
        String responseJson = jsonObject.toString();

        return responseJson ;
    }
    @ApiOperation("下载地址")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", dataType = "String", dataTypeClass = String.class)
    })
    @GetMapping("/user/download")
    public ResponseEntity<FileSystemResource> download(HttpServletRequest request)
    {
        // 指定要下载的文件路径
        String filePath = "/download/release/yourfile.ext"; // 替换为实际文件名和扩展名
        File file = new File(filePath);

        if (!file.exists()) {
            // 如果文件不存在，返回404错误
            return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
        }

        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + file.getName());
        headers.add(HttpHeaders.CONTENT_TYPE, "application/octet-stream");

        // 返回文件作为响应
        return ResponseEntity.ok()
                .headers(headers)
                .body(new FileSystemResource(file));
    }
    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid)
    {
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null)
        {
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha))
        {
            throw new CaptchaException();
        }
    }
}

@ApiModel(value = "UserEntity2", description = "用户实体")
class WotUserEntity
{
    @ApiModelProperty("用户名称")
    @NotNull
    private String username;

    @ApiModelProperty("用户密码")
    @NotNull
    private String password;

    @ApiModelProperty("邮箱")
    @NotNull
    private String email;

    public WotUserEntity()
    {

    }

    public WotUserEntity(String username, String password, String email)
    {
        this.username = username;
        this.password = password;
        this.email = email;
    }

    public String getUsername()
    {
        return username;
    }

    public void setUsername(String username)
    {
        this.username = username;
    }

    public String getPassword()
    {
        return password;
    }

    public void setPassword(String password)
    {
        this.password = password;
    }
    
    public String getEmail()
    {
        return email;
    }

    public void setEmail(String email)
    {
        this.email = email;
    }

}
